package com.yuanlp.mobileplayer.pager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yuanlp.mobileplayer.R;
import com.yuanlp.mobileplayer.activity.SystemVideoPlayer;
import com.yuanlp.mobileplayer.adapter.NetVideoAdapter;
import com.yuanlp.mobileplayer.base.BasePager;
import com.yuanlp.mobileplayer.bean.MediaItem;
import com.yuanlp.mobileplayer.utils.CacheUtils;
import com.yuanlp.mobileplayer.utils.Constants;
import com.yuanlp.mobileplayer.utils.LogUtil;
import com.yuanlp.mobileplayer.view.XListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;


/**
 * Created by 原立鹏 on 2017/7/13.
 * 网络视频的页面
 */

public class NetVideoPager extends BasePager {

    @ViewInject(R.id.listview)   //注解的方式来实例化控件，前提是一定要有下面的那个x.view().inject(this,view);
    private XListView listview;

    @ViewInject(R.id.tv_nonet)
    private TextView nonet;

    @ViewInject(R.id.pb_loading)
    private ProgressBar pb_loading;

    private ArrayList<MediaItem> mediaList;
    private NetVideoAdapter netvideoAdap;

    private boolean isloadMore;

    public NetVideoPager(Context context) {
        super(context);

    }

    /**
     * 强制子类实现特定的效果
     *
     * @return
     */
    @Override
    public View initView() {
        LogUtil.e("网络视频被初始化了");
        View view=View.inflate(context, R.layout.netvideo_pager,null);

        //参数说明，第一个参数是NetVideoPager.this，第二个参数是布局
        x.view().inject(this,view);
        mediaList=new ArrayList<MediaItem>();

        return view;
    }

    @Override
    public void initData() {
        super.initData();
        //获取网络数据
        getData();
        LogUtil.e("网络视频页面的数据被初始化了");

        //获取之前有网络时保存的数据
        String jsonResult=CacheUtils.getString(context,Constants.NET_URL);
        //当有本地数据时，去解析本地数据
        if (!TextUtils.isEmpty(jsonResult)){
            progressData(jsonResult);
        }

        listview.setPullLoadEnable(true);

        listview.setXListViewListener(new MyXListViewListener());


    }

    /**
     * 获取网络数据
     */
    public void getData() {

        RequestParams params=new RequestParams(Constants.NET_URL);
        x.http().get(params, new Callback.CommonCallback<String>() {  //回调公用的一个String
            @Override
            public void onSuccess(String result) {
                LogUtil.e("联网成功"+result);

                //解析数据,获取数据并展示adapter
                progressData(result);

                //将获取的数据保存
                CacheUtils.putString(context,Constants.NET_URL,result);

                //设置item点击事件
                listview.setOnItemClickListener(new MyOnItemClickListener());

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.e("联网失败"+ex.getMessage());
                nonet.setVisibility(View.VISIBLE); //文本显示没网络数据
                pb_loading.setVisibility(View.GONE);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("onCancelled"+cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("onFinished");
            }
        });
    }

    class MyXListViewListener implements XListView.IXListViewListener {

        @Override
        public void onRefresh() {
            getData();

        }
        @Override
        public void onLoadMore() {

            RequestParams params=new RequestParams(Constants.NET_URL);
            x.http().get(params, new Callback.CommonCallback<String>() {  //回调公用的一个String
                @Override
                public void onSuccess(String result) {
                    LogUtil.e("联网成功"+result);
                    isloadMore=true;
                    //解析数据,获取数据并展示adapter
                    progressData(result);

                    listview.setOnItemClickListener(new MyOnItemClickListener());

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    LogUtil.e("联网失败"+ex.getMessage());
                    isloadMore=false;
                    nonet.setVisibility(View.VISIBLE); //文本显示没网络数据
                    pb_loading.setVisibility(View.GONE);

                }

                @Override
                public void onCancelled(CancelledException cex) {
                    LogUtil.e("onCancelled"+cex.getMessage());
                    isloadMore=false;
                }

                @Override
                public void onFinished() {
                    LogUtil.e("onFinished");
                    isloadMore=false;
                }
            });
        }
    }

    /**
     * 重新加载adapter里的数据
     */
    private void onLoad() {
        listview.stopRefresh();
        listview.stopLoadMore();
        listview.setRefreshTime("更新时间"+getSystemTime());
    }

    /**
     * 获取系统时间
     * @return
     */
    private String getSystemTime() {
        SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        return format.format(new Date());
    }

    /**
     * 点击某一条item后，触发这个回调
     */
    class MyOnItemClickListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent=new Intent(context, SystemVideoPlayer.class);
            Bundle bundle=new Bundle();
            bundle.putSerializable("mediallist",(ArrayList<MediaItem>)mediaList);
            intent.putExtras(bundle);
            intent.putExtra("position",position-1);  //将点击的视频的位置传过去，方便定位播放的是哪个视频
            context.startActivity(intent);


        }
    }


    private void progressData(String result) {
        if (!isloadMore){
            mediaList=progressJson(result);
            showData();
            pb_loading.setVisibility(View.GONE);  //progressbar隐藏
        }else{
            //加载更多，那么就把新的list加入到原有的list中
            ArrayList<MediaItem> moreMediaList=progressJson(result);
            mediaList.addAll(moreMediaList);

            //刷新适配器
            netvideoAdap.notifyDataSetChanged();
            isloadMore=false;
            onLoad();

        }
    }

    private void showData() {
        if (mediaList!=null&&mediaList.size()>0){
            nonet.setVisibility(View.GONE);  //隐藏文本

            netvideoAdap = new NetVideoAdapter(context,mediaList);
            //设置适配器
            listview.setAdapter(netvideoAdap);

            onLoad(); //重新加载listview数据
        }else {
            nonet.setVisibility(View.VISIBLE); //文本显示没网络数据
        }
    }


    /**
     * 解析json有2中方法：
     * 1、利用系统接口
     * 2、利用第三方接口，如gson,fastjson
     * @param json
     * @return
     */
    private ArrayList<MediaItem> progressJson(String json) {
        ArrayList<MediaItem> mediaItems=new ArrayList<>();
        //利用系统来解析json
        try {
            JSONObject jsonObject=new JSONObject(json);
            JSONArray trailers = jsonObject.optJSONArray("trailers");//利用这个方法，来获取一个数组
            if (trailers!=null&&trailers.length()>0){
               for (int i=0;i<trailers.length();i++){
                   JSONObject object = (JSONObject) trailers.get(i);
                   if (object!=null){
                       MediaItem item=new MediaItem();
                       String movieName = object.getString("movieName");
                       item.setName(movieName);
                       String videoTitle=object.getString("videoTitle");
                       item.setVideoTitle(videoTitle);
                       String coverImg=object.getString("coverImg");
                       item.setCoverImg(coverImg);
                       String hightUrl=object.getString("hightUrl");
                       item.setData(hightUrl);
                       LogUtil.e("电影名字："+movieName);
                       mediaItems.add(item);
                   }
               }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mediaItems;

    }
}
